#!/bin/bash

echo "🔧 修复 MySQL JSON 兼容性问题..."

# 备份原文件
cp prisma/schema.prisma prisma/schema.prisma.backup

# 创建修复后的 schema.prisma 文件
cat > prisma/schema.prisma << 'EOF'
generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider     = "mysql"
  url          = env("DATABASE_URL")
  relationMode = "prisma"
}

model User {
  id            Int            @id @default(autoincrement())
  username      String         @unique @db.VarChar(50)
  email         String         @unique @db.VarChar(100)
  password      String         @db.VarChar(255)
  realName      String?        @map("real_name") @db.VarChar(100)
  avatar        String?        @db.VarChar(255)
  phone         String?        @db.VarChar(20)
  status        UserStatus     @default(ACTIVE)
  lastLoginAt   DateTime?      @map("last_login_at")
  createdAt     DateTime       @default(now()) @map("created_at")
  updatedAt     DateTime       @updatedAt @map("updated_at")
  userRoles     UserRole[]
  operationLogs OperationLog[]
  
  // 音乐节助手相关关联
  votes         Vote[]
  userBadges    UserBadge[]
  userLocations UserLocation[]
  notifications Notification[]
  notificationSettings UserNotificationSettings?
  assistantConversations AssistantConversation[]

  @@map("users")
}

model Role {
  id              Int              @id @default(autoincrement())
  name            String           @unique @db.VarChar(50)
  description     String?          @db.Text
  permissions     String?          @db.Text // 改为 Text 类型以兼容旧版 MySQL
  status          RoleStatus       @default(ACTIVE)
  createdAt       DateTime         @default(now()) @map("created_at")
  updatedAt       DateTime         @updatedAt @map("updated_at")
  userRoles       UserRole[]
  rolePermissions RolePermission[]

  @@map("roles")
}

model UserRole {
  id        Int      @id @default(autoincrement())
  userId    Int      @map("user_id")
  roleId    Int      @map("role_id")
  createdAt DateTime @default(now()) @map("created_at")
  user      User     @relation(fields: [userId], references: [id], onDelete: Cascade)
  role      Role     @relation(fields: [roleId], references: [id], onDelete: Cascade)

  @@unique([userId, roleId])
  @@map("user_roles")
}

model Permission {
  id              Int              @id @default(autoincrement())
  name            String           @unique @db.VarChar(100)
  code            String           @unique @db.VarChar(100)
  description     String?          @db.Text
  module          String           @db.VarChar(50)
  createdAt       DateTime         @default(now()) @map("created_at")
  updatedAt       DateTime         @updatedAt @map("updated_at")
  rolePermissions RolePermission[]

  @@map("permissions")
}

model RolePermission {
  id           Int        @id @default(autoincrement())
  roleId       Int        @map("role_id")
  permissionId Int        @map("permission_id")
  createdAt    DateTime   @default(now()) @map("created_at")
  role         Role       @relation(fields: [roleId], references: [id], onDelete: Cascade)
  permission   Permission @relation(fields: [permissionId], references: [id], onDelete: Cascade)

  @@unique([roleId, permissionId])
  @@map("role_permissions")
}

model SystemConfig {
  id          Int        @id @default(autoincrement())
  key         String     @unique @db.VarChar(100)
  value       String     @db.Text
  description String?    @db.Text
  type        ConfigType @default(STRING)
  createdAt   DateTime   @default(now()) @map("created_at")
  updatedAt   DateTime   @updatedAt @map("updated_at")

  @@map("system_configs")
}

model OperationLog {
  id         Int      @id @default(autoincrement())
  userId     Int?     @map("user_id")
  action     String   @db.VarChar(100)
  resource   String   @db.VarChar(100)
  resourceId String?  @map("resource_id") @db.VarChar(100)
  details    String?  @db.Text // 改为 Text 类型以兼容旧版 MySQL
  ipAddress  String?  @map("ip_address") @db.VarChar(45)
  userAgent  String?  @map("user_agent") @db.Text
  createdAt  DateTime @default(now()) @map("created_at")
  user       User?    @relation(fields: [userId], references: [id], onDelete: SetNull)

  @@map("operation_logs")
}

// 音乐节助手应用相关模型

model Artist {
  id          Int           @id @default(autoincrement())
  name        String        @db.VarChar(100)
  description String?       @db.Text
  avatar      String?       @db.VarChar(255)
  bannerImage String?       @map("banner_image") @db.VarChar(255)
  genre       String?       @db.VarChar(50)
  country     String?       @db.VarChar(50)
  status      ArtistStatus  @default(ACTIVE)
  createdAt   DateTime      @default(now()) @map("created_at")
  updatedAt   DateTime      @updatedAt @map("updated_at")
  
  // 关联
  performances Performance[]
  votes       Vote[]
  works       ArtistWork[]
  trivia      Trivia[]

  @@map("artists")
}

model Performance {
  id              Int              @id @default(autoincrement())
  artistId        Int              @map("artist_id")
  title           String           @db.VarChar(200)
  description     String?          @db.Text
  venue           String           @db.VarChar(100)
  floor           String?          @db.VarChar(20)
  startTime       DateTime         @map("start_time")
  endTime         DateTime         @map("end_time")
  status          PerformanceStatus @default(SCHEDULED)
  maxCapacity     Int?             @map("max_capacity")
  currentAttendance Int?           @map("current_attendance") @default(0)
  createdAt       DateTime         @default(now()) @map("created_at")
  updatedAt       DateTime         @updatedAt @map("updated_at")
  
  // 关联
  artist          Artist           @relation(fields: [artistId], references: [id], onDelete: Cascade)

  @@map("performances")
}

model Vote {
  id        Int      @id @default(autoincrement())
  userId    Int      @map("user_id")
  artistId  Int      @map("artist_id")
  voteCount Int      @default(1) @map("vote_count")
  createdAt DateTime @default(now()) @map("created_at")
  
  // 关联
  user      User     @relation(fields: [userId], references: [id], onDelete: Cascade)
  artist    Artist   @relation(fields: [artistId], references: [id], onDelete: Cascade)

  @@unique([userId, artistId])
  @@map("votes")
}

model Badge {
  id             Int      @id @default(autoincrement())
  name           String   @db.VarChar(100)
  description    String?  @db.Text
  icon           String?  @db.VarChar(100)
  type           String?  @db.VarChar(50)
  conditionType  String?  @map("condition_type") @db.VarChar(50)
  conditionValue Int?     @map("condition_value")
  createdAt      DateTime @default(now()) @map("created_at")
  
  // 关联
  userBadges     UserBadge[]

  @@map("badges")
}

model UserBadge {
  id        Int      @id @default(autoincrement())
  userId    Int      @map("user_id")
  badgeId   Int      @map("badge_id")
  earnedAt  DateTime @default(now()) @map("earned_at")
  
  // 关联
  user      User     @relation(fields: [userId], references: [id], onDelete: Cascade)
  badge     Badge    @relation(fields: [badgeId], references: [id], onDelete: Cascade)

  @@unique([userId, badgeId])
  @@map("user_badges")
}

model Facility {
  id          Int            @id @default(autoincrement())
  name        String         @db.VarChar(100)
  type        String         @db.VarChar(50)
  floor       String?        @db.VarChar(20)
  locationX   Decimal?       @map("location_x") @db.Decimal(10, 6)
  locationY   Decimal?       @map("location_y") @db.Decimal(10, 6)
  description String?        @db.Text
  status      FacilityStatus @default(OPEN)
  createdAt   DateTime       @default(now()) @map("created_at")
  updatedAt   DateTime       @updatedAt @map("updated_at")

  @@map("facilities")
}

model Trivia {
  id        Int      @id @default(autoincrement())
  title     String   @db.VarChar(200)
  content   String   @db.Text
  category  String?  @db.VarChar(50)
  artistId  Int?     @map("artist_id")
  isActive  Boolean  @default(true) @map("is_active")
  createdAt DateTime @default(now()) @map("created_at")
  
  // 关联
  artist    Artist?  @relation(fields: [artistId], references: [id], onDelete: SetNull)

  @@map("trivia")
}

model AssistantConversation {
  id        Int      @id @default(autoincrement())
  userId    Int      @map("user_id")
  sessionId String   @unique @map("session_id") @db.VarChar(100)
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @updatedAt @map("updated_at")
  
  // 关联
  user      User     @relation(fields: [userId], references: [id], onDelete: Cascade)
  messages  AssistantMessage[]

  @@map("assistant_conversations")
}

model AssistantMessage {
  id             Int                @id @default(autoincrement())
  conversationId Int                @map("conversation_id")
  messageType    AssistantMessageType @map("message_type")
  content        String             @db.Text
  messageFormat  AssistantMessageFormat @default(TEXT) @map("message_format")
  createdAt      DateTime           @default(now()) @map("created_at")
  
  // 关联
  conversation   AssistantConversation @relation(fields: [conversationId], references: [id], onDelete: Cascade)

  @@map("assistant_messages")
}

model UserLocation {
  id        Int      @id @default(autoincrement())
  userId    Int      @map("user_id")
  latitude  Decimal  @db.Decimal(10, 8)
  longitude Decimal  @db.Decimal(11, 8)
  floor     String?  @db.VarChar(20)
  accuracy  Decimal? @db.Decimal(5, 2)
  createdAt DateTime @default(now()) @map("created_at")
  
  // 关联
  user      User     @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@map("user_locations")
}

model Notification {
  id         Int              @id @default(autoincrement())
  userId     Int              @map("user_id")
  title      String           @db.VarChar(200)
  content    String           @db.Text
  type       NotificationType
  isRead     Boolean          @default(false) @map("is_read")
  relatedId  Int?             @map("related_id")
  relatedType String?         @map("related_type") @db.VarChar(50)
  createdAt  DateTime         @default(now()) @map("created_at")
  
  // 关联
  user       User             @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@map("notifications")
}

model UserNotificationSettings {
  id                  Int      @id @default(autoincrement())
  userId              Int      @unique @map("user_id")
  pushEnabled         Boolean  @default(true) @map("push_enabled")
  emailEnabled        Boolean  @default(true) @map("email_enabled")
  performanceReminder Boolean  @default(true) @map("performance_reminder")
  voteReminder        Boolean  @default(true) @map("vote_reminder")
  createdAt           DateTime @default(now()) @map("created_at")
  updatedAt           DateTime @updatedAt @map("updated_at")
  
  // 关联
  user                User     @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@map("user_notification_settings")
}

model ArtistWork {
  id              Int      @id @default(autoincrement())
  artistId        Int      @map("artist_id")
  title           String   @db.VarChar(200)
  duration        String?  @db.VarChar(10)
  description     String?  @db.Text
  releaseDate     DateTime? @map("release_date")
  isRepresentative Boolean @default(false) @map("is_representative")
  createdAt       DateTime @default(now()) @map("created_at")
  
  // 关联
  artist          Artist   @relation(fields: [artistId], references: [id], onDelete: Cascade)

  @@map("artist_works")
}

enum UserStatus {
  ACTIVE
  INACTIVE
  BANNED
}

enum RoleStatus {
  ACTIVE
  INACTIVE
}

enum ConfigType {
  STRING
  NUMBER
  BOOLEAN
  TEXT
}

enum ArtistStatus {
  ACTIVE
  INACTIVE
}

enum PerformanceStatus {
  SCHEDULED
  ONGOING
  COMPLETED
  CANCELLED
}

enum FacilityStatus {
  OPEN
  CLOSED
  MAINTENANCE
}

enum AssistantMessageType {
  USER
  ASSISTANT
}

enum AssistantMessageFormat {
  TEXT
  VOICE
  IMAGE
}

enum NotificationType {
  PERFORMANCE
  VOTE
  SYSTEM
  PROMOTION
}
EOF

echo "✅ Schema 文件已修复"
echo "📁 原文件已备份为 prisma/schema.prisma.backup"
echo "💡 主要修改："
echo "   - 将 Json? 类型改为 String? @db.Text"
echo "   - 将 ConfigType.JSON 改为 ConfigType.TEXT"
echo "   - 保持数据兼容性"

# 重新生成 Prisma 客户端
echo "🔧 重新生成 Prisma 客户端..."
npx prisma generate

echo "✅ 修复完成！"
echo "💡 现在可以运行数据库迁移了"
